package cn.com.anypay.manager.controller.pay;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import cn.com.anypay.manager.config.LeshuaConfig;
import jakarta.annotation.PostConstruct;

import com.fshows.leshuapay.sdk.client.LeshuaPayClient;
import com.fshows.leshuapay.sdk.client.impl.LeshuaPayClientImpl;
import com.fshows.leshuapay.sdk.request.pay.LeshuaQrAndJsPayRequest;
import com.fshows.leshuapay.sdk.request.pay.LeshuaPayQueryRequest;
import com.fshows.leshuapay.sdk.response.pay.LeshuaQrAndJsPayResponse;
import com.fshows.leshuapay.sdk.response.pay.LeshuaPayQueryResponse;
import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping("/api/leshua/wxpay")
public class LeshuaWxpayController {
    private static final Logger log = LoggerFactory.getLogger(LeshuaWxpayController.class);

    @Autowired
    private LeshuaConfig leshuaConfig;

    private LeshuaPayClient<LeshuaQrAndJsPayRequest, LeshuaQrAndJsPayResponse> leshuaPayClient;
    private LeshuaPayClient<LeshuaPayQueryRequest, LeshuaPayQueryResponse> leshuaQueryClient;

    @PostConstruct
    public void init() {
        leshuaPayClient = new LeshuaPayClientImpl<LeshuaQrAndJsPayRequest, LeshuaQrAndJsPayResponse>(
            leshuaConfig.getServiceTradeKey(),
            LeshuaConfig.GATEWAY_URL
        );
        leshuaQueryClient = new LeshuaPayClientImpl<LeshuaPayQueryRequest, LeshuaPayQueryResponse>(
            leshuaConfig.getServiceTradeKey(),
            LeshuaConfig.GATEWAY_URL
        );
    }

    // 创建支付订单
    @PostMapping("/v1/payments")
    public Map<String, Object> createPayment(@RequestBody Map<String, Object> params) {
        try {
            log.info("=== 创建乐刷微信支付订单开始 ===");
            log.info("请求参数: {}", params);

            // 1. 参数验证
            String orderNo = (String) params.get("orderNo");
            String merchantId = leshuaConfig.getMerchantId(); // 使用配置的商户ID
            Double amount = ((Number) params.get("amount")).doubleValue();
            String description = (String) params.get("description");
            String openId = (String) params.get("openId"); // 微信OpenID

            // 2. 生成订单号 (测试用)
            orderNo = String.format("ORDER_%d_%s",
                System.currentTimeMillis(),
                UUID.randomUUID().toString().replace("-", "").substring(0, 8)
            );

            log.info("解析后的参数: orderNo={}, amount={}, description={}, openId={}",
                orderNo, amount, description, openId);

            if (orderNo == null || amount == null || openId == null) {
                log.warn("缺少必要参数7");
                return Map.of(
                    "code", -1,
                    "message", "缺少必要参数8"
                );
            }

            // 3. 验证金额
            if (amount <= 0 || amount > 50000) {
                log.warn("金额无效: {}", amount);
                return Map.of(
                    "code", -1,
                    "message", "金额无效，必须在0-50000之间"
                );
            }

            // 4. 构建乐刷支付请求
            LeshuaQrAndJsPayRequest request = new LeshuaQrAndJsPayRequest();
            request.setThirdOrderId(orderNo);
            request.setAmount(String.valueOf((int)(amount * 100))); // 转换为分
            request.setBody(description);
            request.setMerchantId(merchantId);
            request.setNotifyUrl(leshuaConfig.getNotifyUrl());
            request.setJumpUrl(leshuaConfig.getJumpUrl());
            request.setPayWay("WXZF"); // 微信支付
            request.setJspayFlag("1"); // 微信JS支付（端内H5）
            request.setSubOpenid(openId); // 设置微信OpenID
            request.setClientIp("127.0.0.1"); // 设置客户端IP
            request.setT0("0"); // 设置T0标志
            request.setLimitPay("0"); // 设置支付限制
            request.setRoyalty("0"); // 设置分账标志
            request.setService("get_tdcode"); // 设置服务类型

            log.info("乐刷支付请求参数: {}", request);

            // 5. 调用SDK创建订单
            LeshuaQrAndJsPayResponse response = leshuaPayClient.execute(request, LeshuaQrAndJsPayResponse.class);
            log.info("乐刷支付响应结果: {}", response);

            if ("0".equals(response.getResultCode())) {
                // 解析支付信息
                log.info("乐刷支付 jspayInfo: {}", response.getJspayInfo());
                JSONObject payInfo = JSONObject.parseObject(response.getJspayInfo());
                log.info("乐刷支付解析后的 payInfo: {}", payInfo);

                // 构建支付参数
                Map<String, Object> payParams = new HashMap<>();
                payParams.put("appId", payInfo.getString("appId"));
                payParams.put("timeStamp", payInfo.getString("timeStamp"));
                payParams.put("nonceStr", payInfo.getString("nonceStr"));
                payParams.put("package", payInfo.getString("package"));
                payParams.put("signType", payInfo.getString("signType"));
                payParams.put("paySign", payInfo.getString("paySign"));

                Map<String, Object> data = new HashMap<>();
                data.put("payParams", payParams);

                log.info("乐刷支付返回数据: {}", data);

                return Map.of(
                    "code", 0,
                    "message", "success",
                    "data", data
                );
            } else {
                log.error("创建支付订单失败: code={}, msg={}", response.getErrorCode(), response.getErrorMsg());
                return Map.of(
                    "code", -1,
                    "message", "创建支付订单失败: " + response.getErrorMsg()
                );
            }

        } catch (Exception e) {
            log.error("创建乐刷微信支付订单失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "创建乐刷微信支付订单失败: " + e.getMessage()
            );
        }
    }

    // 查询订单状态
    @GetMapping("/v1/payments/{orderNo}")
    public Map<String, Object> queryPayment(@PathVariable String orderNo) {
        try {
            log.info("=== 查询乐刷微信支付订单状态开始 ===");
            log.info("订单号: {}", orderNo);

            // 1. 构建查询请求
            LeshuaPayQueryRequest request = new LeshuaPayQueryRequest();
            request.setThirdOrderId(orderNo);

            // 2. 调用SDK查询订单
            LeshuaPayQueryResponse response = leshuaQueryClient.execute(request, LeshuaPayQueryResponse.class);

            if (response.getResultCode().equals("0")) {
                return Map.of(
                    "code", 0,
                    "message", "success",
                    "data", Map.of(
                        "orderNo", orderNo,
                        "tradeNo", response.getLeshuaOrderId(),
                        "tradeStatus", response.getStatus(),
                        "totalAmount", response.getAmount()
                    )
                );
            } else {
                return Map.of(
                    "code", -1,
                    "message", "查询订单失败: " + response.getErrorMsg()
                );
            }

        } catch (Exception e) {
            log.error("查询乐刷微信支付订单状态失败: {}", e.getMessage(), e);
            return Map.of(
                "code", -1,
                "message", "查询乐刷微信支付订单状态失败: " + e.getMessage()
            );
        }
    }
}
